package com.darren.euc.job;

import java.io.BufferedReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.naming.NamingException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;

import com.alibaba.fastjson.JSON;
import com.darren.euc.entity.HanWangDoor;
import com.darren.euc.service.HanWangDoorService;
import com.darren.euc.service.HanWangRecordService;
import com.darren.euc.util.StringUtil;

import Com.FirstSolver.Splash.FaceId;
import Com.FirstSolver.Splash.FaceIdAnswer;
import Com.FirstSolver.Splash.FaceId_ErrorCode;
import Com.FirstSolver.Splash.FaceId_Item;



@Component
public class HanWangTask {	

	private static final Logger log = Logger.getLogger(HanWangTask.class);

	@Autowired
    private HanWangDoorService hanWangDoorService;
	
	@Autowired
    private HanWangRecordService hanWangRecordService;	
	
	/**
	 * 读取汉王开门记录
	 * @throws SQLException
	 * @throws NamingException
	 */
	@Scheduled(cron = "0 0/2 * * * ?")
	public void refreshSystemParameter() throws SQLException, NamingException {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		log.info("HanWang face job launch start ..." + System.currentTimeMillis());		
		try {
			//getHanWangRecordsJob();
		} catch (Exception e) {
		    log.error(e.getMessage(),e);
		}	
		log.info("HanWang face job launch end   ..." + System.currentTimeMillis());
		stopWatch.stop();
		log.info("HanWang face job launch total time ..."+ stopWatch.getTotalTimeMillis());
	}
	

	
	private void getHanWangRecordsJob(){
		List<HanWangDoor> hanWangDoors = hanWangDoorService.getAll();
		for(HanWangDoor hanWangDoor:hanWangDoors){
			String ip = StringUtil.convertNullToEmptyString(hanWangDoor.getIp());
			if(!"".equals(ip)){//如果IP为不空，则进行设备检测				
				Integer port = hanWangDoor.getPort();
				String password = StringUtil.convertNullToEmptyString(hanWangDoor.getPassword());	
				String deviceCharset = "GBK";
				try(FaceId tcpClient = new FaceId(ip, port)) {					
		            // 设置设备通信密码(设备管理员密码)
		            tcpClient.setSecretKey(password);

		            // 检测设备是否存在
		            String Command = "DetectDevice()";
		            FaceIdAnswer output = new FaceIdAnswer();
		            FaceId_ErrorCode ErrorCode = tcpClient.Execute(Command, output, deviceCharset);
					if (ErrorCode.equals(FaceId_ErrorCode.Success)) {
						System.out.println(output.answer);
						FaceId_Item[] ItemCollection = FaceId_Item.GetAllItems(output.answer); 
		                if (ItemCollection != null){
		                	for (FaceId_Item item : ItemCollection){
		                		if("result".equals(item.name) && "success".equals(item.value)){
		                			hanWangDoor.setConnectStatus(1);//成功检测到设备存在，更新设备状态为已连接
		                			break;
		                		}
		                		System.out.println(item.name + ":" + item.value);
		                	}
		                }
					} else {
						System.out.println("设备检测失败！");
					}
				} catch (Exception e) {
					System.out.println("连接设备失败！");
					System.out.println(e.getMessage());
				}
			}			
			hanWangDoor.setLastConnectTime(new Date());
			hanWangDoorService.update(hanWangDoor);
		}
	}
	
	
	/**
	 * 定时刷新汉王门禁设备连接状态
	 * @throws SQLException
	 * @throws NamingException
	 */
	//@Scheduled(cron = "0 0/30 * * * ?")
	@Scheduled(cron = "0 0/5 * * * ?")
	public void refreshHanWangConnectionStatus() throws SQLException, NamingException {
		StopWatch stopWatch = new StopWatch();
		stopWatch.start();
		log.info("HanWang connection status job launch start ..." + System.currentTimeMillis());		
		try {
			refreshConnectionStatus();
		} catch (Exception e) {
		    log.error(e.getMessage(),e);
		}	
		log.info("HanWang connection status job launch end   ..." + System.currentTimeMillis());
		stopWatch.stop();
		log.info("HanWang connection status job launch total time ..."+ stopWatch.getTotalTimeMillis());
	}
	
	private void refreshConnectionStatus(){		
		List<HanWangDoor> hanWangDoors = hanWangDoorService.getAll();
		for(HanWangDoor hanWangDoor:hanWangDoors){
			String ip = StringUtil.convertNullToEmptyString(hanWangDoor.getIp());
			hanWangDoor.setConnectStatus(2);//先设置设备状态为未连接 2；等下面设备连接成功，才更新其状态为已连接  1
			if(!"".equals(ip)){//如果IP为不空，则进行设备检测				
				Integer port = hanWangDoor.getPort();
				String password = StringUtil.convertNullToEmptyString(hanWangDoor.getPassword());	
				String deviceCharset = "GBK";
				try(FaceId tcpClient = new FaceId(ip, port)) {					
		            // 设置设备通信密码(设备管理员密码)
		            tcpClient.setSecretKey(password);

		            // 检测设备是否存在
		            String Command = "DetectDevice()";
		            FaceIdAnswer output = new FaceIdAnswer();
		            FaceId_ErrorCode ErrorCode = tcpClient.Execute(Command, output, deviceCharset);
					if (ErrorCode.equals(FaceId_ErrorCode.Success)) {
						System.out.println(output.answer);
						FaceId_Item[] ItemCollection = FaceId_Item.GetAllItems(output.answer); 
		                if (ItemCollection != null){
		                	for (FaceId_Item item : ItemCollection){
		                		if("result".equals(item.name) && "success".equals(item.value)){
		                			hanWangDoor.setConnectStatus(1);//成功检测到设备存在，更新设备状态为已连接
		                			break;
		                		}
		                		System.out.println(item.name + ":" + item.value);
		                	}
		                }
					} else {
						System.out.println("设备检测失败！");
					}
				} catch (Exception e) {
					System.out.println("连接设备失败！");
					System.out.println(e.getMessage());
				}
			}
			hanWangDoorService.updateHanWangConnectionStatus(hanWangDoor.getId(),hanWangDoor.getConnectStatus());
		}
	}
	
	
}
